package com.hj.auth.controller;

import com.hj.auth.common.convert.UserConvert;
import com.hj.auth.common.pojo.LoginUser;
import com.hj.auth.common.pojo.entity.User;
import com.hj.auth.common.pojo.vo.UserVO;
import com.hj.auth.common.util.JwtTokenUtil;
import com.hj.auth.service.UserService;
import com.hj.common.constant.Constants;
import com.hj.common.pojo.model.AjaxResult;
import com.hj.common.util.ServletUtils;
import com.hj.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 登陆 : 返回token
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody UserVO userVO) {
        if (StringUtils.isEmpty(userVO.getUserName())){
            return AjaxResult.error("用户名为空");
        }
        if (StringUtils.isEmpty(userVO.getPassWord())){
            return AjaxResult.error("密码为空");
        }

        //校验用户信息 返回token
        String newToken = userService.login(userVO.getUserName(),userVO.getPassWord());
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN,newToken);
        return ajax;
    }

    /**
     * 获取用户信息
     * @return
     */
    @PreAuthorize("@per.hasPermission('auth:user:query')")//判断用户是否具备该权限
    @GetMapping("/findByUser")
    public AjaxResult findByUser(){
        LoginUser loginUser = jwtTokenUtil.getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(loginUser);
    }

    /**
     * 修改用户信息
     * @return
     */
    @PreAuthorize("@per.hasPermission('auth:user:update')")
    @PutMapping("/updateUserById")
    public AjaxResult updateUserById(@RequestBody UserVO userVO) {
        if (StringUtils.objCheckIsNull(userVO)){
            return AjaxResult.error("请传参 !!!");
        }
        User user = UserConvert.INSTANCE.vo2entity(userVO);
        //修改用户信息
        int i = userService.updateUser(user);
        return AjaxResult.success("修改成功");
    }

}
